package com.lzy.arithmetic;

/**
 * Author: lzy
 * Date:   2020/06/10 15:27
 * Description:
 **/
public class 二分查找 {

    public static void main(String[] args) {
        int[] array = new int[]{1, 3, 5, 7, 9, 11, 56, 89};
        int target = 100;
        System.out.println("递归：" + getIndexDG(array, target));
        System.out.println("非递归：" + getIndexNotDG(array, target, 0, array.length));
    }

    public static int getIndexDG(int[] array, int target) {
        int left = 0;
        int right = array.length - 1;

        while (left <= right) {
            int mid = left + (right - left) / 2;
            int num = array[mid];
            if (target == num) {
                return mid;
            } else if (target < num) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return -1;
    }

    public static int getIndexNotDG(int[] array, int target, int left, int right) {
        if(left >= right){
            return -1;
        }
        int mid = left + (right - left) / 2;
        int num = array[mid];
        if(target == num){
            return mid;
        }else if(target < num){
            return getIndexNotDG(array, target, left, mid - 1);
        }else{
            return getIndexNotDG(array, target, mid + 1, right);
        }
    }
}
